<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3.手写深度比较</title>
</head>

<body>
  手写深度比较，模拟lodash isEqual

  <script>
    // 实现如下效果
    // const obj1 = { a: 10, b: { x: 100, y: 200 } }
    // const obj2 = { a: 10, b: { x: 100, y: 200 } }
    // isEqual(obj1, obj2) === true

    const obj1 = { a: 10, b: { x: 100, y: 200} }
    const obj2 = { a: 10, b: { x: 100, y: 200 } }
    function isObject(obj) {
      return typeof obj === 'object' && obj !== null
    }
    // 全相等（深度比较）
    function isEqual(obj1, obj2) { 
      if (!isObject(obj1) || !isObject(obj2)) {
        // 1.值类型 
        return obj1 === obj2
      }
      // 2.判断是否是同一个对象
      if (obj1 === obj2) {
        return true
      }
      // 3.判断key数量是否一直
      const obj1Keys = Object.keys(obj1)
      const obj2Keys = Object.keys(obj2)
      if (obj1Keys.length !== obj2Keys.length) {
        return false
      }

      // 4.深度比较,以obj1为基准，和obj2比较
      for (let key in obj1) { 
        const res = isEqual(obj1[key], obj2[key])
        if (!res) {
          return false
        }
      }
      return true
    }
    const arr1 = [1,2,3,4]
    const arr2 = [1,2,3]

    console.log(isEqual(arr1, arr2));




  </script>

</body>

</html>